package org.hishenframework.web.pager;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.hishenframework.data.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HishenPagerTag extends TagSupport {
	
	private static final long serialVersionUID = 1L;
	/** 当前页面KEY，用于分页 */
	private static final String CURRENT_PAGE_NAME = "currentPage";
	/** 数据名称 */
	private static final String PAGE_NAME = "page";
	
	private Logger logger = LoggerFactory.getLogger(HishenPagerTag.class);

	private Page page;
	
	private String action;
	
	private long showPageNumber = 5;
	
	@Override
	public int doStartTag() throws JspException {
		//TODO: 可以尝试用用
//		ScriptEngineManager manager = new ScriptEngineManager();
//		ScriptEngine engine = manager.getEngineByName("js");
//		//engine.put("age", 21);
//		try {
//			engine.eval("var age = 17;" +
//					"if (age > 18) {" +
//					"	print('Old enough');" +
//					"} else {" +
//					"	print('too young');" +
//					"}");
//		} catch (ScriptException e1) {
//			e1.printStackTrace();
//		}

		Page page = this.page;
		if (page == null) {
			page = (Page) pageContext.getRequest().getAttribute(PAGE_NAME);
		}
		if (page == null) {
			page = (Page) pageContext.getSession().getAttribute(PAGE_NAME);
		}
		if (page == null) {
			page = (Page) pageContext.getServletContext().getAttribute(PAGE_NAME);
		}
		if (page == null) {
			logger.warn("Can't found 'dataPaging' in any scope!");
			return SKIP_BODY;
		}
		
		StringBuilder alinkBuilder = new StringBuilder();
		ServletRequest request = pageContext.getRequest();
		Enumeration<String> en = request.getParameterNames();
		while (en.hasMoreElements()) {
			String name = en.nextElement();
			if (CURRENT_PAGE_NAME.equals(name)) {
				continue;
			}
			String value = request.getParameter(name);
			alinkBuilder.append("&" + name + "=" + value);
			
		}
		alinkBuilder.append("&currentPage=");
		String action = this.action;
		//创建当前路径的
		if (action == null) {
			HttpServletRequest request2 = (HttpServletRequest) request;
			action = request2.getRequestURI().replaceAll("/WEB-INF/page/app", "");
			action = action.substring(0, action.lastIndexOf("/"));
		}
		
		if (action.indexOf("?") == -1) {
			alinkBuilder.delete(0, 1);
			alinkBuilder.insert(0, "?");
		}
		alinkBuilder.insert(0, "<li><a href=\"" + action);
		
		
		JspWriter out = pageContext.getOut();
		try {
//			out.write("<label class='hs-name-pager-totalcount'>" + page.getTotalCount() + " 条记录</label>");
//			out.write(" <label class='hs-name-pager-totalpagers'>共" + page.getTotalPages() + "页</label> ");
			out.write("<ul class=\"pagination pull-right\">");
			String alink = alinkBuilder.toString();
			if (page.getCurrentPage() > 1) {
				//显示第一页
				out.write(alink + "1\">首页</a> ");
				//显示上一页
				out.write(alink + (page.getCurrentPage() - 1) + "\">上一页</a></li> ");
			} else {
				out.write("<li class=\"disabled\"><a href=\"javascript:void(0)\">首页</a> ");
				out.write("<li class=\"disabled\"><a href=\"javascript:void(0)\">上一页</a></li> ");
			}
			
			long begin, end;
			boolean isMore = false;
			long addPageCount = showPageNumber / 2;
			//当页面数小于等于显示行数
			if (page.getTotalPages() <= showPageNumber) {
				begin = 1;
				end = page.getTotalPages() + 1;
			} else {
				if (page.getCurrentPage() <= addPageCount) {
					begin = 1;
					end = showPageNumber + 1;
					isMore = true;
				} else if (page.getTotalPages() - page.getCurrentPage() <= addPageCount) {
					begin = page.getTotalPages() - showPageNumber + 1;
					end = page.getTotalPages() + 1;
				} else {
					begin = page.getCurrentPage() - addPageCount;
					end = page.getCurrentPage() + addPageCount;
					//翻页显示单数时，补1页
					end = showPageNumber % 2 == 1 ? end + 1 : end;
					isMore = true;
				}
			}
			
			while(begin < end) {
				if (begin == page.getCurrentPage()) {
					out.write("<li class=\"active\"><a href=\"javascript:void(0)\">" + begin + "</a></li> ");	
				} else { 
					out.write(alink + begin + "\">" + begin + "</a></li> ");
				}
				begin++;
			}
			//显示页码省略号
			if (isMore) {
				out.write("<li><a href=\"#\">...</a>");
			}
			//显示下一页
			if(page.getTotalPages() > page.getCurrentPage()) {
				out.write(alink + (page.getCurrentPage() + 1) + "\">下一页</a></li>");
				out.write(" " + alink + (page.getTotalPages()) + "\">末页</a></li>");
			} else {
				out.write("<li class=\"disabled\"><a href=\"javascript:void(0)\">下一页</a> ");
				out.write("<li class=\"disabled\"><a href=\"javascript:void(0)\">末页</a></li> ");
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}


	public void setShowPageNumber(long showPageNumber) {
		this.showPageNumber = showPageNumber;
	}

	public void setAction(String action) {
		this.action = action;
	}


	public void setPage(Page page) {
		this.page = page;
	}

}